package com.lyl.myaiagent.servertools.tools;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lyl
 * @version 1.0
 * @CreateTime: 2025-08-19
 */
@Slf4j
public class WebSearchTool {
    private static final String url = "https://www.searchapi.io/api/v1/search";


    private final String searchApiKey;

    public WebSearchTool(String searchApiKey) {
        this.searchApiKey = searchApiKey;
    }

    @Tool(description = "search for web information from baidu engine")
    public String searchWeb(@ToolParam(description = "search query keyword") String query) {
        log.info("开始根据关键词搜索网页");
        // 构建请求参数
        Map<String, Object> params = new HashMap<>();
        params.put("q", query);
        params.put("api_key", searchApiKey);
        params.put("engine", "baidu");

        // 发送HTTP请求
        String response = HttpUtil.get(url, params);

        // 解析JSON响应
        try {
            var jsonObject = JSONUtil.parseObj(response);
            var organicResults = jsonObject.getJSONArray("organic_results");
            // 只取前5条结果
            var result = organicResults.stream()
                    .limit(5)
                    .toList();
            log.info("根据关键词搜索网页完成！");
            return JSONUtil.toJsonStr(result);

        } catch (Exception e) {
            log.error("根据关键词搜索网页有误");
            return "Error searching baidu：" + e.getMessage(); // 如果没有结果或解析失败，返回信息
        }
    }
}
